package com.google.code.bankagregator.ui;

import com.google.code.bankagregator.core.DataManager;
import com.google.code.bankagregator.entities.Currency;
import com.google.code.bankagregator.entities.Deposit;
import com.google.code.bankagregator.vo.DepositOffer;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "deposit", urlPatterns = {"/deposit"})
public class DepServlet extends HttpServlet {

    /**
     * Enterprise JavaBean
     * <p/>
     * Please use *dataManager* only (for get and put operations with Core).
     */
    @EJB
    DataManager dataManager;

    public int getInt(String param) {
        int res = 0;
        if ((!param.equals("")) && (!param.contains(" "))) {
            res = Integer.parseInt(param);
        }
        return res;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Deposit> deposits = new ArrayList<>();

        if(request.getParameter("all") != null) {
            deposits = dataManager.getAllActiveDeposits();
            request.setAttribute("deposits", deposits);
            request.getRequestDispatcher("allDeposit.jspx").forward(request, response);
        } else
        {
            String termStr = request.getParameter("term");
            String currencyStr = request.getParameter("currency");
            String amountStr = request.getParameter("amount");

            Deposit deposit = new Deposit();

            int term = getInt(termStr);
            int amount = getInt(amountStr);

            Currency currency = Currency.valueOf(currencyStr);

            deposit.setTerm(term);
            deposit.setCurrency(currency);
            List<DepositOffer> dep = new ArrayList<>();

            dep = dataManager.getSuitableDepositOffers(deposit,amount);

            request.setAttribute("amount", amount);
            request.setAttribute("dep", dep);
            request.getRequestDispatcher("deposit.jspx").forward(request, response);

    }
    }}
